﻿using liaowa2.Utils;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace liaowa2.Api.App_Start
{
    /// <summary>
    /// 
    /// </summary>
    public class OpenAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        /// <summary>
        /// 验证客户[client_id与client_secret验证]
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string client_id;
            string client_secret;
            context.TryGetFormCredentials(out client_id, out client_secret);

            string md5String = EncodeSecurity.Md5Security(client_id);

            if (md5String == client_secret)
            {
                context.Validated(client_id);
            }
            else
            {
                context.SetError("client_id与client_secret验证失败");
            }
            return base.ValidateClientAuthentication(context);

        }

        /// <summary>
        /// 客户端授权[生成access token]
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {

            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "liaowa2.0"));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties() { AllowRefresh = true });
            context.Validated(ticket);
            return base.GrantClientCredentials(context);

        }

    }
}